package com.example.tetstmybatis.service;

import com.example.tetstmybatis.domain.User2;
import com.example.tetstmybatis.domain.User2Example;
import com.example.tetstmybatis.mapper.User2Mapper;
import com.example.tetstmybatis.req.*;
import com.example.tetstmybatis.resp.CommonResp;
import com.example.tetstmybatis.resp.User2LoginResp;
import com.example.tetstmybatis.resp.User2QueryResp;
import com.example.tetstmybatis.utils.CopyUtil;
import com.example.tetstmybatis.utils.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class User2Service {
    @Resource
   private User2Mapper user2Mapper;
    @Resource
    private SnowFlake snowFlake;
   public User2LoginResp login(User2LoginReq req){
       User2 user2Db = selectByLoginName(req.getLoginName());
       if(ObjectUtils.isEmpty(user2Db)){
           //用户名不存在
           return null;
           //用户名或密码错误
       }else{
           //判断前端传进来的密码与数据库中的密码是否相等
           if(req.getPassword().equals(user2Db.getPassword()) ){
               //用户名与密码是合法，
               //登录
               User2LoginResp user2LoginResp = CopyUtil.copy(user2Db, User2LoginResp.class);
               return user2LoginResp;
           }else {
               //密码不正确
               return null;
               //用户名或密码错误
           }
       }
   }

     public User2 selectByLoginName(String loginName){
         User2Example user2Example = new User2Example();
         User2Example.Criteria criteria = user2Example.createCriteria();
         criteria.andLoginNameEqualTo(loginName);
         List<User2> user2s = user2Mapper.selectByExample(user2Example);
         if(CollectionUtils.isEmpty(user2s)){
             return null;
         }else{
             return user2s.get(0);
         }
     }

    public boolean register(User2RegisterReq req){
        User2 user2 = CopyUtil.copy(req, User2.class);
        user2.setId(snowFlake.nextId());//
        int insert = user2Mapper.insert(user2);
        if (insert==0){
            // 添加失败
            return false;
        }else{
            //添加成功
            return true;
        }
    }

    public CommonResp listall(User2QueryReq req){
        User2Example user2Example = new User2Example();
        User2Example.Criteria criteria = user2Example.createCriteria();
        if(!ObjectUtils.isEmpty(req.getLoginName())){
            criteria.andLoginNameEqualTo(req.getLoginName());
        }
        List<User2> user2s = user2Mapper.selectByExample(user2Example);//
        List<User2QueryResp> user2QueryResps = CopyUtil.copyList(user2s, User2QueryResp.class);//
        CommonResp objectCommonResp = new CommonResp();
        objectCommonResp.setContent(user2QueryResps);
        return objectCommonResp;
    }

}
